package swing;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;

import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.WindowConstants;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

// import controlador.ControladorAdmListasPrecios;
import controlador.ControladorAdmStock;

// import rmi.ProxyModeloConcreto;

// import ViewObjects.ItemLPView;
import ViewObjects.ItemRemitoView;
// import ViewObjects.ListaPreciosView;
import ViewObjects.RemitoView;
import ViewObjects.RodamientoView;


/**
* This code was edited or generated using CloudGarden's Jigloo
* SWT/Swing GUI Builder, which is free for non-commercial
* use. If Jigloo is being used commercially (ie, by a corporation,
* company or business for any purpose whatever) then you
* should purchase a license for each developer using Jigloo.
* Please visit www.cloudgarden.com for details.
* Use of Jigloo implies acceptance of these licensing terms.
* A COMMERCIAL LICENSE HAS NOT BEEN PURCHASED FOR
* THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED
* LEGALLY FOR ANY CORPORATE OR COMMERCIAL PURPOSE.
*/
public class StockAlta extends Vista {
	/**
	 * 
	 */
	private static final long serialVersionUID = 979630615942906626L;
	private JTextField jTextFieldDir;
	private JButton jButton;
	private JLabel jLabelMensaje;
	private JButton jButtonSalir;
	private JButton jButtonAlta;
	private Document dom;

	@Override
	public void actualizar() {
		// TODO Auto-generated method stub
		
	}
	
	public StockAlta() {
		super();
		initGUI();
	}

	private void initGUI() {
		try {
			{
				setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
				getContentPane().setLayout(null);
				this.setSize(468, 191);
				this.setTitle("Alta Stock - Carga de Remito");
				this.setVisible(true);
			}
			{
				jTextFieldDir = new JTextField();
				getContentPane().add(jTextFieldDir);
				jTextFieldDir.setBounds(12, 51, 356, 23);
			}
			{
				jButton = new JButton();
				getContentPane().add(jButton);
				jButton.setText("...");
				jButton.setBounds(388, 51, 41, 23);
				jButton.addActionListener(new ActionListener() {
					public void actionPerformed(ActionEvent evt) {
						abrirBusqueda();
						}	
					} 
				);
				
			}
			{
				jLabelMensaje = new JLabel();
				getContentPane().add(jLabelMensaje);
				jLabelMensaje.setText("Ingrese Directorio y nombre del Remito .XML");
				jLabelMensaje.setBounds(12, 18, 349, 16);
			}
			{
				jButtonAlta = new JButton();
				getContentPane().add(jButtonAlta);
				jButtonAlta.setText("Alta Stock");
				jButtonAlta.setBounds(239, 111, 103, 23);
				jButtonAlta.addActionListener(new ActionListener() {
					public void actionPerformed(ActionEvent evt) {
						altaStockRemito();
						}	
					} 
				);
			}
			{
				jButtonSalir = new JButton();
				getContentPane().add(jButtonSalir);
				jButtonSalir.setText("Salir");
				jButtonSalir.setBounds(361, 111, 68, 23);
				jButtonSalir.addActionListener(new ActionListener() {
					public void actionPerformed(ActionEvent evt) {
						dispose();
						}	
					} 
				);
			}
		} catch(Exception e) {
			e.printStackTrace();
		}
	}
	
	public void abrirBusqueda(){
		JFileChooser fileChooser = new JFileChooser();
		int seleccion = fileChooser.showOpenDialog(this);
		if (seleccion == JFileChooser.APPROVE_OPTION)
		{
		   File fichero = fileChooser.getSelectedFile();
		   String path = fichero.getPath();
		   jTextFieldDir.setText(path);
		}
	}
	
	public void altaStockRemito() {

		//parse the xml file and get the dom object
		parseXmlFile(jTextFieldDir.getText());
	
		//get each employee element and create a Employee object
		parseDocument();
	
	}
	
	public void parseXmlFile(String path){
	
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		
		try {
			
			//Using factory get an instance of document builder
			DocumentBuilder db = dbf.newDocumentBuilder();
			
			//parse using builder to get DOM representation of the XML file
			dom = db.parse(path);
			
		}catch(ParserConfigurationException pce) {
			pce.printStackTrace();
		}catch(SAXException se) {
			se.printStackTrace();
		}catch(IOException ioe) {
			ioe.printStackTrace();
		}
	}

	private void parseDocument(){
		Set<ItemRemitoView> itemsRemito = new HashSet<ItemRemitoView>();
		
		//obtengo el elemento raiz
		Element docEle = dom.getDocumentElement();
		
		//obtengo la cabecera de la Lista de Precios
		NodeList nl = docEle.getElementsByTagName("Cabecera");
		Element el = (Element)nl.item(0);
		
		//obtengo el objeto ListaPreciosView
		RemitoView rem = getRemitoView(el);
		
		//obtengo los Items de la Lista de Precio
		NodeList nl1 = docEle.getElementsByTagName("ItemRemito");
		
		if(nl1 != null && nl1.getLength() > 0) {
			for(int i = 0 ; i < nl1.getLength();i++) {
				
				//obtengo el elemento empleado
				Element el1 = (Element)nl1.item(i);
				
				//obtengo el objeto empleado
				ItemRemitoView ir = getItemRemito(el1);
				
				//add it to list
				itemsRemito.add(ir);
			}
		}
		rem.setItems(itemsRemito);

		ControladorAdmStock p  = (ControladorAdmStock) this.controlador;
		p.doAlta_Stock(rem);
		
	}

	private RemitoView getRemitoView(Element cabecera) {
	
		int idProveedor = getIntValue(cabecera,"idProveedor");
		int idOrdenCompra = getIntValue(cabecera,"idOrdenCompra");
		int nroRemito = getIntValue(cabecera,"nroRemito");
		String fechaV = getTextValue(cabecera,"fecha");
		@SuppressWarnings("static-access")
		java.sql.Date fecha = new java.sql.Date(0).valueOf(fechaV);
	
		//Crea la Lista de PreciosView a partir de los atributos.
		RemitoView rem = new RemitoView();
		
		rem.setIdProveedor(idProveedor);
		rem.setNroRemito(nroRemito);
		rem.setIdOrdenCompra(idOrdenCompra);
		rem.setFecha(fecha);
	
		return rem;
	}

	private ItemRemitoView getItemRemito(Element itemrem) {
		
		// TODO Auto-generated method stub
		int cantidad = getIntValue(itemrem,"cantidad");
		String codigoFabricante = getTextValue(itemrem,"codigoFabricante");
	
		//Crea un Item del RemitoView a partir de los atributos.
		ItemRemitoView ir = new ItemRemitoView();
		RodamientoView r = new RodamientoView();
		
		ir.setCantidad(cantidad);
		r.setCodigoSFK(codigoFabricante);
		
		ir.setRodamiento(r);
		
		return ir;
		
	}
		
	private String getTextValue(Element ele, String tagName) {
		String textVal = null;
		NodeList nl = ele.getElementsByTagName(tagName);
		if(nl != null && nl.getLength() > 0) {
			Element el = (Element)nl.item(0);
			textVal = el.getFirstChild().getNodeValue();
		}
		return textVal;
	}

	private int getIntValue(Element ele, String tagName) {
		//in production application you would catch the exception
		//System.out.println(getTextValue(ele, tagName));
		return Integer.parseInt(getTextValue(ele,tagName));
	}
	/*
	private float getFloatValue(Element ele, String tagName) {
		//in production application you would catch the exception
		//System.out.println(getTextValue(ele, tagName));
		return Float.parseFloat(getTextValue(ele,tagName));
	}**/
	/**
	* This method should return an instance of this class which does 
	* NOT initialize it's GUI elements. This method is ONLY required by
	* Jigloo if the superclass of this class is abstract or non-public. It 
	* is not needed in any other situation.
	 */
	public static Object getGUIBuilderInstance() {
		return new StockAlta(Boolean.FALSE);
	}
	
	/**
	 * This constructor is used by the getGUIBuilderInstance method to
	 * provide an instance of this class which has not had it's GUI elements
	 * initialized (ie, initGUI is not called in this constructor).
	 */
	public StockAlta(Boolean initGUI) {
		super();
	}
	
}
